import request from './request'
import type { EntityData, PageQuery, PageResult } from '@/types/entity'
import type { ApiResponse } from '@/types/api'

/**
 * 通用CRUD API基类
 */
export class BaseCrudApi<T extends EntityData = EntityData> {
  private baseUrl: string
  private hasCompositePrimaryKey: boolean

  constructor(tableName: string, hasCompositePrimaryKey: boolean = false) {
    this.baseUrl = `/$${r"{tableName}"}`
    this.hasCompositePrimaryKey = hasCompositePrimaryKey
  }

  /**
   * 查询所有记录
   */
  async findAll(): Promise<T[]> {
    const response = await request.get<ApiResponse<T[]>>(this.baseUrl)
    return response.data.data
  }

  /**
   * 根据ID查询单条记录
   */
  async findById(id: any): Promise<T> {
    if (this.hasCompositePrimaryKey) {
      // 复合主键使用POST方式
      const response = await request.post<ApiResponse<T>>(`$${r"{this.baseUrl}"}/findById`, id)
      return response.data.data
    } else {
      // 单主键使用GET方式
      const response = await request.get<ApiResponse<T>>(`$${r"{this.baseUrl}"}/$${r"{id}"}`)
      return response.data.data
    }
  }

  /**
   * 分页查询
   */
  async findByPage(query: PageQuery): Promise<PageResult<T>> {
    const params = {
      current: query.current,
      size: query.size
    }
    const response = await request.get<ApiResponse<PageResult<T>>>(`$${r"{this.baseUrl}"}/page`, { params })
    return response.data.data
  }

  /**
   * 创建新记录
   */
  async create(data: Partial<T>): Promise<T> {
    const response = await request.post<ApiResponse<T>>(this.baseUrl, data)
    return response.data.data
  }

  /**
   * 更新记录
   */
  async update(id: any, data: Partial<T>): Promise<T> {
    if (this.hasCompositePrimaryKey) {
      // 复合主键直接PUT到根路径
      const response = await request.put<ApiResponse<T>>(this.baseUrl, data)
      return response.data.data
    } else {
      // 单主键PUT到/{id}
      const response = await request.put<ApiResponse<T>>(`$${r"{this.baseUrl}"}/$${r"{id}"}`, data)
      return response.data.data
    }
  }

  /**
   * 删除记录
   */
  async deleteById(id: any): Promise<void> {
    if (this.hasCompositePrimaryKey) {
      // 复合主键使用POST方式删除
      await request.delete(`$${r"{this.baseUrl}"}/deleteById`, { data: id })
    } else {
      // 单主键使用路径参数删除
      await request.delete(`$${r"{this.baseUrl}"}/$${r"{id}"}`)
    }
  }

  /**
   * 批量删除
   */
  async deleteAll(ids: any[]): Promise<void> {
    await request.delete(this.baseUrl, { data: ids })
  }

  /**
   * 检查记录是否存在
   */
  async existsById(id: any): Promise<boolean> {
    const response = await request.get<ApiResponse<boolean>>(`$${r"{this.baseUrl}"}/$${r"{id}"}/exists`)
    return response.data.data
  }

  /**
   * 统计记录总数
   */
  async count(): Promise<number> {
    const response = await request.get<ApiResponse<number>>(`$${r"{this.baseUrl}"}/count`)
    return response.data.data
  }

  /**
   * 根据字段查询
   */
  async findByField(fieldName: string, value: any): Promise<T[]> {
    const response = await request.get<ApiResponse<T[]>>(`$${r"{this.baseUrl}"}/by-$${r"{fieldName.toLowerCase()}"}`, {
      params: { [fieldName]: value }
    })
    return response.data.data
  }
}

/**
 * 创建实体API实例的工厂函数
 */
export function createEntityApi<T extends EntityData = EntityData>(
  tableName: string, 
  hasCompositePrimaryKey: boolean = false
): BaseCrudApi<T> {
  return new BaseCrudApi<T>(tableName, hasCompositePrimaryKey)
}